<template>
  <page-lr class="page-pollution-source-emission page-create-pollution-events">
      <template slot="content-left">
        <div :style="{width:'100%',height: domHeight + 'px' ,overflow:'hidden',position:'relative',}">
          <map-box ref="mapBox" :dom-height="domHeight" :is-pronvince="false" :is-city="true" />
          <el-collapse v-model="activeNames" class="map-tips">
            <el-collapse-item title="污染事件（面和点）" name="1">
              <div class="top">高</div>
              <div class='bar'></div>
              <div class="bottom">低</div>
            </el-collapse-item>
            <el-collapse-item title="国控站点" name="2">
              <img :src="iconUrl" />
            </el-collapse-item>
          </el-collapse>
        </div>
      </template>
      <div slot="content-right" class="search-block">
        <el-form size="small" :model="searchForm" label-width="100px">
          <el-form-item label="选择日期：">
            <el-date-picker v-model="searchForm.gen_date" type="date" value-format="yyyy-MM-dd" placeholder="选择年" :picker-options="pickerDate" style="width:100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="应对指标：">
            <el-button v-for="(item,index) in initData.pollutants" :key="index" size="small" :type="searchForm.pollutant == item.value ? 'primary' : 'default'" @click="searchForm.pollutant = item.value">
              {{ item.label }}
            </el-button>
          </el-form-item>
          <el-form-item label="应对等级：">
            <el-button v-for="(item,index) in initData.levels" :key="index" size="small" :type="searchForm.level == item.value ? 'primary' : 'default'" @click="searchForm.level = item.value">
              {{ item.label }}
            </el-button>
          </el-form-item>
          <el-form-item label="应对站点：">
            <el-button v-for="(item,index) in initData.stations" :key="index" size="small" :type="searchForm.station_id == item.station_id ? 'primary' : 'default'" @click="searchForm.station_id = item.station_id">
              {{ item.name }}
            </el-button>
          </el-form-item>
          <el-button type="primary" size="medium" style="width:100%" @click="handleEvent(false)">生成污染事件</el-button>
        </el-form>
        <div class="m-t-10" v-if="!userInfo.is_region_user">
          <el-button type="default" size="medium" style="width:100%" @click="handleEvent(true)">保存污染事件</el-button>
        </div>
      </div>
  </page-lr>
</template>
<script>
import '@/assets/js/jquery.min.js';
import mapboxgl from 'mapbox-gl';
import * as turf from '@turf/turf';
import MapBox from '@/components/MapBox';
import {city,cityId,cityPinyin,geoserver} from '@/config/env';
import axios from 'axios';
export default {
  components:{
    MapBox
  },
  data(){
    return{
      loading: false,
      searchForm:{
        gen_date: '',
        pollutant: 'o3',
        level: 3,
        limit: 800,
        // save_to_db: false,
        station_id: 0,
        name: null,
      },
      pickerDate:{
        disabledDate: null
      },
      domHeight: null,
      initData:{
        pollutants: [
          { label: 'O₃', value: 'o3', alias: 'O3' },
          { label: 'NOx', value: 'nox', alias: 'NOx' },
          { label: 'PM', value: 'pm', alias: 'PM' }
        ],
        levels: [
          { label: 'Ⅱ级', value: 2 },
          { label: 'Ⅲ级', value: 3 },
        ],
        stations: [],
      },
      list: [],
      iconUrl: require('@/assets/images/icons/atmosphere-environmental-point-cn-1.png'),
      map: null,
      activeNames: ['1', '2'],
      userInfo:{},
    }
  },
  created(){
    this.isRegionUser();
    this.getInitData();
  },
  methods:{
    isRegionUser(){
      this.userInfo = this.$store.getters.currentUserInfo;
    },
    async getInitData(){
      this.domHeight = document.body.clientHeight - 64 - 40 - 48*2 - 10;
      this.searchForm.gen_date = this.$moment().format('YYYY-MM-DD');
      this.pickerDate.disabledDate = (time) => {
        const current = new Date(this.$moment().add(7, 'd')).getTime();
        const start = new Date('2022-12-31').getTime();
        return time.getTime() > current || time.getTime() < start;
      }
      this.initData.stations = await this.$request('get', '/air/stations', {});
      let id = String(this.initData.stations[0].station_id).substring(0,5);
      this.searchForm.station_id = Number(id);
      this.initData.stations.unshift({station_id: Number(id), name: '全市站点'});
      this.map = this.$refs.mapBox.map;
      this.addStationLayer();
    },
    getName(){
      let d = this.searchForm.gen_date.replace(/-/g, '');
      let station = this.initData.stations.find(item => item.station_id == this.searchForm.station_id);
      let pollutant = this.initData.pollutants.find(item => item.value == this.searchForm.pollutant);
      let level = this.initData.levels.find(item => item.value == this.searchForm.level);
      let name = d+ '-' + station.name + pollutant.alias + level.label + '应对';
      return name;
    },
    async handleEvent(isSave){
      this.loading = true;
      this.searchForm.name = this.getName();
      this.list = await this.$request('get', '/stations/pollute_incidence_add', {...this.searchForm, save_to_db: false});
      if(isSave){
        await this.$request('get', '/stations/pollute_incidence_add', {...this.searchForm, save_to_db: true});
        this.$message.success('保存污染事件成功');
      }
      await this.addStationLayer();
      this.addPolluteLayer();
      this.addComanyLayer();
      // this.map.moveLayer('company-layer','station-layer','city-border')
    },
    addStationLayer() {
      if (!this.map) {
        return;
      }
      if (this.map.getLayer('station-layer')) {
        this.map.setFilter('station-layer',
          this.searchForm.station_id
            ? ['==', 'station_id', this.searchForm.station_id] : null
        )
        return;
      }
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      for (const d of this.initData.stations) {
        geojson.features.push({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [d.lon, d.lat]
          },
          properties: d
        });
      }
      this.map.loadImage(this.iconUrl, (error, image) => {
        if (error) throw error;
        if (!this.map.hasImage('atmosphere-environmental-point-cn-1')) this.map.addImage('atmosphere-environmental-point-cn-1', image);
        this.map.addLayer({
          id: 'station-layer',
          type: 'symbol',
          source: {
            type: 'geojson',
            data: geojson
          },
          paint: {
            'text-color': '#fff',
            'text-halo-color': 'rgb(0,0,0)',
            'text-halo-width': 1,
          },
          layout: {
            'icon-image': 'atmosphere-environmental-point-cn-1',
            'icon-size': .75,
            'icon-allow-overlap': true,
            'icon-ignore-placement': true,
            'text-field': ['get', 'name'],
            'text-anchor': 'bottom',
            'text-offset': [0, -1.5],
            'text-justify': 'auto',
            'text-size': 14,
          }
        });
      });
    },

    addPolluteLayer() {
      if (!this.map) {
        return;
      }
      if (this.map.getLayer('guokong-imprint-layer')) {
        this.map.removeLayer('guokong-imprint-layer');
      }
      if (this.map.getSource('guokong-imprint')) {
        this.map.removeSource('guokong-imprint');
      }
      if (!this.searchForm.station_id) {
        return;
      }
      let url = geoserver + '/hesil/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hesil:fp_view_test2&outputFormat=application/json&'
        + 'viewparams=update_time:' + `${this.searchForm.gen_date}`;
      url += `;station_id:${this.searchForm.station_id}`;
      this.map.addSource('guokong-imprint', {
        type: 'geojson',
        data: url
      });
      const before = this.map.getLayer('company-layer') ? 'company-layer' :
        this.map.getLayer('station-layer') ? 'station-layer' : undefined;
      this.map.addLayer({
        id: 'guokong-imprint-layer',
        type: 'fill',
        source: 'guokong-imprint',
        paint: {
          'fill-antialias': true,
          'fill-color': {
            property: 'conc',
            stops: [
              [0.5, 'RGB(66,1,158)'],
              [0.6, 'RGB(79,62,213)'],
              [0.8, 'RGB(67,109,244)'],
              [1, 'RGB(97,174,253)'],
              [2, 'RGB(139,224,254)'],
              [5, 'RGB(173,246,255)'],
              [8, 'RGB(191,255,255)'],
              [12, 'RGB(152,245,230)'],
              [18, 'RGB(164,221,171)'],
              [25, 'RGB(165,194,102)'],
              [35, 'RGB(189,136,50)'],
              [50, 'RGB(162,79,94)']
            ],
          },
        }
      }, before);
      this.map.moveLayer('guokong-imprint-layer','city-border');
      this.fitBounds(url);
      
    },

    addComanyLayer() {
      if (!this.map) {
        return;
      }
      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      for (const d of this.list) {
        geojson.features.push({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [d.lon, d.lat]
          },
          properties: d
        });
      }
      if (this.map.getSource('company-layer')) {
        (this.map.getSource('company-layer')).setData(geojson);
      }
      const conc = this.list.map(i => Number(i.conc)).sort();
      const max = conc.length > 0 ? conc[conc.length - 1] : 0;
      const colors = [
        'RGB(66,1,158)',
        'RGB(79,62,213)',
        'RGB(67,109,244)',
        'RGB(97,174,253)',
        'RGB(139,224,254)',
        'RGB(173,246,255)',
        'RGB(191,255,255)',
        'RGB(152,245,230)',
        'RGB(164,221,171)',
        'RGB(165,194,102)',
        'RGB(189,136,50)',
        'RGB(162,79,94)'
      ];
      const dem = max / colors.length;
      const linear = [
        'interpolate',
        ['linear'],
        ['to-number', ['get', 'conc']],
      ];
      for (let index = 0; index < colors.length; index++) {
        linear.push(index*dem, colors[index]);
      }
      if (this.map.getLayer('company-layer')) {
        this.map.setPaintProperty('company-layer', 'circle-color', linear);
        return;
      }
      this.map.addLayer({
        id: 'company-layer',
        type: 'circle',
        source: {
          type: 'geojson',
          data: geojson
        },
        paint: {
          'circle-color': linear,
          'circle-stroke-width': 1,
          'circle-stroke-color': '#000',
        }
      }, this.map.getLayer('station-layer') ? 'station-layer' : undefined);
      
      this.addPopup();
    },

    async fitBounds(url){
      if (!this.map) {
        return;
      }
      const res = await this.$request('get',url, {});
      console.log('res', res);
      const box = turf.bbox(res);
      this.map.fitBounds([[box[0], box[1]], [box[2], box[3]]], {
        padding: 75,
        linear: false,
        animate: false
      });
    },
    // fitBounds(url){
    //   if (!this.map) {
    //     return;
    //   }
    //   $.getJSON(url, (data) => { // 解决跨域问题
    //     const box = turf.bbox(data);
    //     this.map.fitBounds([[box[0], box[1]], [box[2], box[3]]], {
    //       padding: 75,
    //       linear: false,
    //       animate: false
    //     });
    //   });
    // },

    addPopup() {
      const popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false
      });
      this.map.on('mouseenter', 'company-layer', (e) => {
        this.map.getCanvas().style.cursor = 'pointer';
        const coordinates = e.features[0].geometry.coordinates.slice();
        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
          coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
        }
        const prop = e.features[0].properties;
        let html = `<div class="map-popup-container">`;
        html += `<div class="popup-title">污染源详情</div>`;
        html += '<div class="popup-content"><table class="popup-table" style="width:360px;">';
        html += `<tr><td width="90px">企业名称</td><td>${prop.name}</td></tr>`;
        html += `<tr><td>所属区县</td><td>${prop.county}</td></tr>`;
        html += `<tr><td>所属镇街</td><td>${prop.town}</td></tr>`;
        html += `<tr><td>行业类型</td><td>${prop.class}</td></tr>`;
        html += '</table></div>'
        html += '</div>';
        popup.setLngLat(coordinates)
          .setHTML(html)
          .addTo(this.map);
      });
      this.map.on('mouseleave', 'company-layer', () => {
        this.map.getCanvas().style.cursor = '';
        popup.remove();
      });
    }
  }
}
</script>